package com.fruit.service.queue.impl;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fruit.constants.ActivityConstant;
import com.fruit.constants.QueueConstant;
import com.fruit.pojo.queue.Cache;
import com.fruit.pojo.queue.MultilParams;
import com.fruit.pojo.queue.QueueParams;
import com.fruit.sdk.account.commission.MultilevelRebateService;
import com.fruit.service.order.QueueHandel;
import com.fruit.service.promotion.ActivityManager;
import com.fruit.service.promotion.impl.LockManager;
import com.fruit.service.queue.QueueBusHandel;
import com.fruit.service.redis.JedisUtil;
import com.fruit.util.ResultInfo;
import com.fruit.util.ResultUtil;
import com.joe.utils.parse.json.JsonParser;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * 队列处理逻辑类（无事物）
 *
 * @author shibeilei
 * @version 2017.12.01 10:12
 *
 */
@Slf4j
@Service
public class QueueBusHandelNothing implements QueueBusHandel {

	@Autowired
	private JedisUtil jedisService;

	@Autowired
	private QueueHandel queueService;

	@Autowired
	private LockManager lockService;

	@Autowired
	private ActivityManager activityService;

	@Autowired
	private MultilevelRebateService multilevelRebateService;

	private static final JsonParser JSON = JsonParser.getInstance();

	@Override
	public Map<String, Object> handel(QueueParams params) {
		String tradeId = params.getTradeId();
		try {
			log.info("[{}]-【队列】-【处理开始】", tradeId);
			log.info("[{}]-【队列】-【参数:{}】", tradeId, params);
			// multil 处理多级返利
			String type = params.getType();
			if ("multil_user".equals(type)) {
				MultilParams multilParams = (MultilParams) params;
				Map<String, Object> resMap = new HashMap<String, Object>();
				Lock lock = null;
				try {

					log.info("[{}]-【活动用户锁】", tradeId);
					lock = lockService.getLock(ActivityConstant.ACTIVITY_MULTIL_USER + multilParams.getUserId());
					lock.lock();
					resMap = activityService.saveActivityUserRelation(tradeId, multilParams.getTransId(),
							multilParams.getActivityId(), multilParams.getUserId(), multilParams.getGoodsId(), multilParams.getPrice());
					return resMap;
				} catch (Exception e) {
					log.error("[{}]-【初始化活动用户信息】-【异常---{}】", tradeId, e);
					resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "exception", "初始化活动用户信息异常!"));
					return resMap;
				} finally {
					log.info("[{}]-【释放活动用户锁】", tradeId);
					if (lock != null) {
						lock.unlock();
					}
					ResultInfo ri = (ResultInfo) resMap.get("result");
					if (ResultInfo.ERROR.equals(ri.getState())) {
						log.info("[{}]-【初始化活动用户信息】-【失败】", tradeId);
					}else{
						multilParams.setType("multil_rebate");
						saveQueue(multilParams);
					}
					
				}
			} else if ("multil_rebate".equals(type)) {
				log.info("[{}]-【队列】-【处理开始】-【多级分润处理】", tradeId);
				MultilParams multilParams = (MultilParams) params;
				Map<String, Object> resMap = new HashMap<String, Object>();
				Lock lock = null;
				try{
				log.info("[{}]-【多级分润活动锁】", tradeId);
				lock = lockService.getLock(ActivityConstant.ACTIVITY_MULTIL + multilParams.getActivityId());
				lock.lock();
				resMap = multilevelRebateService.doMultilevelRebate(tradeId,
						multilParams.getUserId(), multilParams.getPrice(),
						multilParams.getTransId(), multilParams.getActivityId(), multilParams.getGoodsId());

				return resMap;
				}catch(Exception e){
					log.error("[{}]-【多级分润处理】-【异常---{}】", tradeId, e);
					resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "exception", "多级分润处理异常!"));
					return resMap;
				}finally{
					log.info("[{}]-【释放多级分润活动锁】", tradeId);
					if (lock != null) {
						lock.unlock();
					}
					ResultInfo ri = (ResultInfo) resMap.get("result");
					if (ResultInfo.ERROR.equals(ri.getState())) {
						log.info("[{}]-【多级分润处理】-【失败】", tradeId);
					}
				}

			} else {
				log.error("[{}]-【队列】-【处理异常】-【未找到类型】", tradeId);
				return null;
			}
		} catch (Exception e) {
			log.error("[{}]-【队列】-【处理异常】-【异常:{}】", tradeId, e);
			return null;
		}
	}

	@Override
	public void saveQueue(QueueParams params) {
		String tradeId = params.getTradeId();
		try {
			log.info("[{}]-【插入队列】-【开始】", tradeId);
			log.info("[{}]-【插入队列】-【参数:{}】", tradeId, params);
			// multil 多级返利插入队列

			log.info("[{}]-【插入队列】-【多级分润】", tradeId);

			String type = params.getType();
			if ("multil_user".equals(type) || "multil_rebate".equals(type)) {
				MultilParams multilParams = (MultilParams) params;
				// 封装参数
				String key = type + multilParams.getTransId();
				params.setKey(key);
				Cache cache = new Cache();
				cache.setClassName(params.getClass().getName());
				cache.setData(JSON.toJson(params));
				cache.setKey(key);

				// 插入redis
				jedisService.hset(QueueConstant.MULTIL_PROFIT, key, JSON.toJson(cache));
				// 插入队列
				queueService.add(params, true);
				log.info("[{}]-【插入队列】-【多级分润】-【成功】", tradeId);
			}

		} catch (Exception e) {
			log.error("[{}]-【插入队列】-【异常:{}】", tradeId, e);
		}
	}
	
	public void saveRedis(QueueParams params) {
		String tradeId = params.getTradeId();
		try {
			log.info("[{}]-【插入缓存】-【开始】", tradeId);
			log.info("[{}]-【插入缓存】-【参数:{}】", tradeId, params);
			// multil 多级返利插入队列

			log.info("[{}]-【插入缓存】-【多级分润】", tradeId);

			String type = params.getType();
			if ("multil_user".equals(type) || "multil_rebate".equals(type)) {
				MultilParams multilParams = (MultilParams) params;
				// 封装参数
				String key = type + multilParams.getTransId();
				params.setKey(key);
				Cache cache = new Cache();
				cache.setClassName(params.getClass().getName());
				cache.setData(JSON.toJson(params));
				cache.setKey(key);

				// 插入redis
				jedisService.hset(QueueConstant.MULTIL_PROFIT, key, JSON.toJson(cache));
				log.info("[{}]-【插入缓存】-【多级分润】-【成功】", tradeId);
			}

		} catch (Exception e) {
			log.error("[{}]-【插入缓存】-【异常:{}】", tradeId, e);
		}
	}	

}
